# ******************************************************************************
#  Copyright (c) 2021-2022. Kneron Inc. All rights reserved.                   *
# ******************************************************************************

from .KPEnum import ApiReturnCode
from typing import Any
import inspect


class ApiException(Exception):
    """
    This class represents a base Exception thrown when a call to the KneronPLUS API fails.
    In addition to an informative message, it has a `function_name` and a `result` attribute, which respectively
    contain the name of the failed function and the returned result that made the function to be considered  as
    failed.
    """

    def __init__(self, api_return_code: ApiReturnCode, msg: str, function_name: str, result: Any = None):
        super(ApiException, self).__init__(msg)
        self.api_return_code = api_return_code
        self.function_name = function_name
        self.result = result


class ApiKPException(ApiException):
    """
    This class represents an Exception thrown when a KneronPLUS API returns error code.
    """

    def __init__(self, api_return_code: ApiReturnCode, function_name: str, result: Any = None):
        super(ApiKPException, self).__init__(
            api_return_code,
            "Error raised in function: {}. Error code: {}. Description: {}".format(function_name,
                                                                                   api_return_code.value,
                                                                                   str(api_return_code)),
            function_name,
            result)


def _check_api_return_code(result: Any, api_return_code: ApiReturnCode) -> None:
    if api_return_code != ApiReturnCode.KP_SUCCESS:
        raise ApiKPException(
            api_return_code=api_return_code,
            function_name=inspect.stack()[1][3],
            result=result)
